﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MedicinaMuncii.Entities;
using MedicinaMuncii.BL.Contracts;
using MedicinaMuncii.IoC;

namespace MedicinaMuncii.UI.Mvc.Controllers
{
    public class EmployeeController : BaseController
    {
        IEmployeeService employeeService;
        ICompanyService companyService;
        IPersonService personService;
        IAddressService addressService;

        #region Constructor
        public EmployeeController()
        {
            employeeService = IoCWorker.Resolve<IEmployeeService>();
            companyService = IoCWorker.Resolve<ICompanyService>();
            personService = IoCWorker.Resolve<IPersonService>();
            addressService = IoCWorker.Resolve<IAddressService>();
        }
        #endregion Constructor

        public ActionResult Index()
        {
            IList<Employee> employees = employeeService.GetAll(new string[] { "company", "person" });
            return View(employees);
        }

        public ActionResult Create()
        {
            ViewData["Companies"] = companyService.GetAll();
            return View();  
        }

        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            // Automatically asign the next available number in the company
            if (employee.Number == null)
            {
                employee.Number = employeeService.GetNextAvailableNumber(employee.CompanyID);
            }

            try
            {
                employeeService.Add(employee);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                ViewData["Companies"] = companyService.GetAll();
                return View();
            }
        }

        public ActionResult Edit(int id)
        {
            ViewData["Companies"] = companyService.GetAll();
            Employee employee = employeeService.GetByID(e => e.ID == id, new string[] { "person", "person.address" });
            return View(employee);
        }

        [HttpPost]
        public ActionResult Edit(Employee employee)
        {
            try
            {
                addressService.Update(employee.person.address);
                personService.Update(employee.person);
                employeeService.Update(employee);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            employeeService.Delete(e => e.ID == id);
            return RedirectToAction("Index");
        }
    }
}
